package com.wd.tw.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.util.UUID;

/**
 * @className: ImageUtils
 * @description: TODO 类描述
 * @author: liumingkun
 * @date: 2024/3/26
 **/
public class ImageUtils {

    private final static Logger logger = LoggerFactory.getLogger(ImageUtils.class);

    public static String uploadImage(String base64Image, String uploadPath) throws IOException {
        if (base64Image == null) // 图像数据为空
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        // Base64解码
        byte[] bytes = decoder.decodeBuffer(base64Image);
        for (int i = 0; i < bytes.length; ++i) {
            if (bytes[i] < 0) {// 调整异常数据
                bytes[i] += 256;
            }
        }
        String newFileName = UUID.randomUUID() + ".jpg";
        String filePath;
        if (CommonUtils.isOSLinux()) {
            filePath = uploadPath + newFileName;
        } else {
            filePath = System.getProperty("user.dir") + uploadPath + newFileName;
        }
        // 生成jpeg图片
        OutputStream out = new FileOutputStream(filePath);
        out.write(bytes);
        out.flush();
        out.close();
        //====
        return newFileName;

    }


    /**
     * 获取图片：Base64
     *
     * @param fileName
     * @param uploadPath
     * @return
     * @throws IOException
     */
    public static String loadBase64Image(String fileName, String uploadPath) {
        byte[] data = new byte[0];
        try {
            data = loadImage(fileName, uploadPath);
            BASE64Encoder encoder = new BASE64Encoder();
            // 去除标准中的回车符
            return encoder.encode(data).replaceAll("[\\s*\t\n\r]", "");
        } catch (IOException e) {
            logger.info(e.getMessage());
            return null;
        }

    }

    /**
     * 获取图片：byte[]
     *
     * @param fileName
     * @param uploadPath
     * @return
     * @throws IOException
     */
    public static byte[] loadImage(String fileName, String uploadPath) throws IOException {

        File file;
        if (CommonUtils.isOSLinux()) {
            file = new File(uploadPath + fileName);
        } else {
            file = new File(System.getProperty("user.dir") + uploadPath + fileName);
        }
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes, 0, inputStream.available());
        return bytes;
    }


}
